from AIAssistant import AIAssistant
from DataAnalysisAssistant import DataAnalysisAssistant
from ImageGenerationAssistant import ImageGenerationAssistant
from TextGenerationAssistant import TextGenerationAssistant
from TranslationAssistant import TranslationAssistant
from VoiceAssistant import VoiceAssistant
from typing import List, Optional

class AIManager:
    """AI助手管理器"""

    def __init__(self, max_size: int):
        self.assistant_array: List[Optional[AIAssistant]] = [None] * max_size
        self.count = 0
        self.init_default_assistants()

    def init_default_assistants(self) -> None:
        """初始化默认助手"""
        # 修复3: 修正参数顺序，与构造函数定义匹配
        self.add_assistant(VoiceAssistant("101", "小智", "v1.2", True, 85, "中文,英文"))
        self.add_assistant(TextGenerationAssistant("102", "文小助", "v2.0", True, 92, "诗歌,文案,报告"))
        self.add_assistant(ImageGenerationAssistant("103", "图灵", "v1.5", False, 88, "4K,8K"))
        self.add_assistant(DataAnalysisAssistant("104", "数小析", "v1.0", True, 79, "CSV,Excel,JSON"))
        self.add_assistant(TranslationAssistant("105", "翻译精灵", "v2.1", False, 95, "中英,中日,中韩"))

    def add_assistant(self, assistant: AIAssistant) -> str:
        """添加新助手"""
        if self.count >= len(self.assistant_array):
            return "❌ 系统容量不足，无法添加新助手！"

        if self.find_assistant_by_id(assistant.get_id()) is not None:
            return f"❌ ID为{assistant.get_id()}的助手已存在，添加失败！"

        self.assistant_array[self.count] = assistant
        self.count += 1
        return f"✅ 助手【{assistant.get_name()}】添加成功！"

    def find_assistant_by_id(self, aid: str) -> Optional[AIAssistant]:
        """根据ID查找助手"""
        for assistant in self.assistant_array:
            if assistant is not None and assistant.get_id() == aid:
                return assistant
        return None

    def get_all_assistants(self) -> List[AIAssistant]:
        """获取所有助手列表"""
        return [assistant for assistant in self.assistant_array if assistant is not None]

    def update_assistant(self, aid: str, property_: str, value: str) -> str:
        """更新助手信息"""
        assistant = self.find_assistant_by_id(aid)
        if assistant is None:
            return f"❌ 未找到ID为{aid}的助手，修改失败！"

        property_lower = property_.lower()
        if property_lower == "name":
            assistant.set_name(value)
        elif property_lower == "type":
            assistant.set_type(value)
        elif property_lower == "version":
            assistant.set_version(value)
        elif property_lower == "online":
            assistant.set_online(value == "1")
        elif property_lower == "score":
            try:
                score = int(value)
                if 0 <= score <= 100:
                    assistant.set_ability_score(score)
                else:
                    return "❌ 能力评分需在0-100之间，修改失败！"
            except ValueError:
                return "❌ 评分需为数字，修改失败！"
        else:
            return f"❌ 不支持修改属性：{property_}，可修改属性为：name,type,version,online,score"

        return f"✅ 助手【{aid}】修改成功！"

    def delete_assistant(self, aid: str) -> str:
        """删除助手"""
        assistant = self.find_assistant_by_id(aid)
        if assistant is None:
            return f"❌ 未找到ID为{aid}的助手，删除失败！"

        # 查找并删除目标助手
        index = -1
        for i in range(len(self.assistant_array)):
            if self.assistant_array[i] is not None and self.assistant_array[i].get_id() == aid:
                index = i
                break

        if index != -1:
            self.assistant_array[index] = None
            self.count -= 1

            # 整理数组，将None移到末尾
            for j in range(index, len(self.assistant_array) - 1):
                self.assistant_array[j] = self.assistant_array[j + 1]
                self.assistant_array[j + 1] = None

        return f"✅ 助手【{assistant.get_name()}】已删除。"

    # 修复4: 添加缺失的方法定义
    def start_assistant(self, aid: str) -> str:
        """启动助手服务"""
        assistant = self.find_assistant_by_id(aid)
        if assistant is None:
            return f"❌ 未找到ID为{aid}的助手，启动失败！"
        if assistant.get_is_online():
            return f"❌ 助手【{assistant.get_name()}】已经处于在线状态！"
        assistant.set_online(True)
        return f"✅ 助手【{assistant.get_name()}】服务已启动！"

    def stop_assistant(self, aid: str) -> str:
        """停止助手服务"""
        assistant = self.find_assistant_by_id(aid)
        if assistant is None:
            return f"❌ 未找到ID为{aid}的助手，停止失败！"
        if not assistant.get_is_online():
            return f"❌ 助手【{assistant.get_name()}】已经处于离线状态！"
        assistant.set_online(False)
        return f"✅ 助手【{assistant.get_name()}】服务已停止！"

    def assign_task(self, aid: str, task_content: str) -> str:
        """分配任务给助手"""
        assistant = self.find_assistant_by_id(aid)
        if assistant is None:
            return f"❌ 未找到ID为{aid}的助手，任务分配失败！"
        if not assistant.get_is_online():
            return f"❌ 助手【{assistant.get_name()}】当前离线，无法执行任务！"
        return assistant.execute_task(task_content)

    def get_statistics(self) -> str:
        """获取系统统计信息"""
        total = len(self.assistant_array)
        active = sum(1 for a in self.assistant_array if a is not None and a.get_is_online())
        inactive = sum(1 for a in self.assistant_array if a is not None and not a.get_is_online())
        avg_score = sum(a.get_ability_score() for a in self.assistant_array if a is not None) / self.count if self.count > 0 else 0
        
        return (f"系统统计信息：\n" \
                f"- 总容量: {total}\n" \
                f"- 当前助手数量: {self.count}\n" \
                f"- 在线助手: {active}\n" \
                f"- 离线助手: {inactive}\n" \
                f"- 平均能力评分: {avg_score:.1f}/100")